#include "OriBodyRecvRelayHandler.h"
#include "OriBodySendRelayHandler.h"

using namespace log4cplus;

Logger OriBodyRecvRelayHandler::log=GetLogger(LOG4CPLUS_TEXT("OriBodyRecvRelayHandler"));

ITransHandler::ExecuteResultCode OriBodyRecvRelayHandler::Execute(ClientContext &client,OVERLAPPED *ovl)
{
	unsigned int clienSequenceNo=client.SequenceNo();
	LOG4CPLUS_DEBUG_FMT(log,LOG4CPLUS_TEXT("[Client%d]Start to relay original server receive."),clienSequenceNo);
	DWORD recvCount=-1;
	DWORD flags;
	BOOL result=::WSAGetOverlappedResult(client.DestSock(),client.OVL(),&recvCount,true,&flags);
	int errCode=::WSAGetLastError();
	if(result)
	{
		if(recvCount==0)
		{
			LOG4CPLUS_DEBUG_FMT(log,LOG4CPLUS_TEXT("[Client%d]Receive 0 byte data,exit."),clienSequenceNo);
			return ITransHandler::ExecuteFinished;
		}
		else
		{
			LOG4CPLUS_DEBUG_FMT(log,LOG4CPLUS_TEXT("[Client%d]Receive %d bytes data,begin to translate."),clienSequenceNo,recvCount);
			delete client.SetCurrentHandler(GetNextHandler());
			client.WeakRefBuffer()->buf=client.Buffer()->buf;
			client.WeakRefBuffer()->len=recvCount;
			::ZeroMemory(client.OVL(),sizeof(OVERLAPPED));
			int sendResult=::WSASend(client.SrcSock(),client.WeakRefBuffer(),1,NULL,0,client.OVL(),NULL);
			errCode=::WSAGetLastError();
			if(sendResult!=0&&errCode!=WSA_IO_PENDING)
			{
				LOG4CPLUS_ERROR_FMT(log,LOG4CPLUS_TEXT("[Client%d]Begin translate data failed,error code:%d."),clienSequenceNo,errCode);
				return ITransHandler::ExecuteFatalError;
			}
		}
	}
	else
	{
		LOG4CPLUS_ERROR_FMT(log,LOG4CPLUS_TEXT("[Client%d]Receive data failed,error code:%d."),clienSequenceNo,errCode);
		return ITransHandler::ExecuteFatalError;
	}
	return ITransHandler::ExecuteOK;
}

ITransHandler* OriBodyRecvRelayHandler::GetNextHandler()
{
	return new OriBodySendRelayHandler();
}